<template>
  <!-- 时段模板批量设置限制条件管理 ---- 模板条件批量设置 -->
  <div class="ky-container" @click="appoRuleDlgClose">
    <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
      <el-form ref="ruleForm" :model="formData" :inline="true" label-width="80px" class="ky-form-inline ky-form-inline-sm" :rules="rules">
        <el-form-item label="医院名称" prop="hospitalCode">
          <el-select
            size="small"
            v-model="formData.hospitalCode"
            placeholder="请选择"
            filterable
            @change="handleChange('hospital')">
            <el-option
              v-for="(item,index) in mx_hospitalList"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像区域">
          <el-select
            size="small"
            v-model="formData.depArea"
            placeholder="请选择"
            clearable
            @change="handleChange('depArea')">
            <el-option
              v-for="(item,index) in depAreaOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查部门">
          <el-select
            size="small"
            v-model="formData.dep"
            placeholder="请选择"
            clearable
            @change="handleChange('dep')">
            <el-option
              v-for="(item,index) in scheduledDepOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查设备">
          <el-select
            size="small"
            v-model="formData.modality"
            placeholder="请选择"
            clearable
            @change="handleChange('modality')">
            <el-option
              v-for="(item,index) in modalityOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查机房">
          <el-select
            size="small"
            v-model="formData.checkRoom"
            placeholder="请选择"
            clearable>
            <el-option
              v-for="(item,index) in checkRoomOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查班次">
          <el-select
            size="small"
            v-model="formData.checkClass"
            multiple
            placeholder="请选择"
            clearable
            collapse-tags>
            <el-option
              v-for="(item,index) in formOptions.checkClassOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="星期">
          <el-select
            size="small"
            v-model="formData.week"
            multiple
            placeholder="请选择"
            clearable
            collapse-tags>
            <el-option
              v-for="(item,index) in formOptions.weekOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            size="small"
            v-model="formData.status"
            placeholder="请选择"
            clearable>
            <el-option
              v-for="(item,index) in statusOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查时间">
          <el-time-select
            style="width: 105px"
            placeholder="起始"
            v-model="formData.beginTime"
            :picker-options="startTimePickerOption">
          </el-time-select>
          <el-time-select
            style="width: 105px"
            placeholder="结束"
            v-model="formData.endTime"
            :picker-options="endTimePickerOption">
          </el-time-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="serach1">查询</el-button>
          <el-button class="m-l-0 click-button" size="small" @click="resetParam" plain>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="quickfilter-content ky-mt10">
      <el-card v-show="quickFilterStatus" shadow="hover" class="qf-sidebar ky-card ky-card-hdbg">
        <div class="content-title" style="line-height: 34px;">
          <span>快速查询</span>
          <i class="el-icon-arrow-left ky-fr ky-pointer ky-ft16 ky-fw600" style="margin-top: 10px;" @click="quickFilterStatus = false"></i>
        </div>
        <HospAreaDepFilter
          ref="hospAreaDepFilter"
          :hospital-code="formData.hospitalCode"
          @treeChange="treeChange"></HospAreaDepFilter>
      </el-card>
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg">
        <div class="content-title">
          <i class="el-icon-arrow-right ky-pointer ky-ft16 ky-fw600" v-show="!quickFilterStatus" @click="quickFilterStatus = true"></i>
          <span class="tit">模板时段列表</span>
          <div class="ky-inlineblock">
            <el-button
              class="title_btn"
              type="primary"
              size="small"
              v-permission="'YJYY10001001004'"
              :disabled="totalCount===0"
              @click.stop="appoAllRuleChange">批量修改 <b>{{totalCount}}</b> 条模板时段【条件】</el-button>
          </div>
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          size="medium"
          :data="tableData"
          style="width: 100%"
          border
          class="ky-table"
        >
          <!-- <el-table-column prop="hospitalName" label="医院" min-width="170"></el-table-column> -->
          <el-table-column prop="depArea" label="院区"></el-table-column>
          <el-table-column prop="dep" label="部门"></el-table-column>
          <el-table-column prop="modality" label="设备"></el-table-column>
          <el-table-column prop="modalityType" label="设备类型"></el-table-column>
          <el-table-column prop="checkRoom" label="机房" min-width="120"></el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
              <div class="status_tag" :class="statusFlr(scope.row.status)">{{scope.row.status}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="checkNum" label="检查数量" width="80"></el-table-column>
          <el-table-column prop="initialNum" label="初始" width="80"></el-table-column>
          <el-table-column prop="reserveNum" label="预留" width="80"></el-table-column>
          <el-table-column prop="addNum" label="追加" width="80"></el-table-column>
          <el-table-column prop="checkClass" label="班次" width="80"></el-table-column>
          <el-table-column prop="week" label="星期" width="80"></el-table-column>
          <el-table-column prop="beginTime" label="时段时间" width="140">
            <template slot-scope="scope">
              <span>{{scope.row.beginTime}}-{{scope.row.endTime}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="checkGroup" label="机房分组" width="80"></el-table-column>
          <el-table-column prop="operatorName" label="操作人员" width="110"></el-table-column>
          <el-table-column prop="operatorDate" label="操作时间" width="180" :formatter="dateFormatterTime"></el-table-column>
          <el-table-column label="操作" fixed="left" width="100">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center">
                <el-button type="warning" size="small" @click="handleLog(scope.row)"><i class="el-icon-tickets"></i>日志</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="changePagenation"
        />
      </el-card>
    </div>
    <!-- 时段模板日志 -->
    <appoPeriodLog
      :hospital-code="formData.hospitalCode"
      :appo-period-log-dlg.sync="appoPeriodLogDlg"
      :id="appoLogId"
      tabel-type="2">
    </appoPeriodLog>
    <!-- 修改时段限制条件 -->
    <ruleTemplateDlg
      rule-type="2"
      @appoRuleEidtCb="appoAllRuleEditSend"
      ref="ruleTemplateDlg">
    </ruleTemplateDlg>
  </div>
</template>

<script>
import {
  postAppTempAdvancepages,
  getDepAreaList,
  getDepList,
  getModalityList,
  getCheckRoomList,
  putAppTempDmbsetfilters
} from '@/api/api'
import paginationCont from '@/components/Pagination/index'
import appoPeriodLog from '@/components/logDialog/appoPeriodLog'
import HospAreaDepFilter from '@/components/treeFilter/hospitalAreaDepTree'
import ruleTemplateDlg from '../components/ruleTemplateDlg'
import { dateFormatter } from '@/utils/validate'
import { Options } from '@/utils/constant'
export default {
  name: '',
  components: { paginationCont, appoPeriodLog, ruleTemplateDlg, HospAreaDepFilter },
  data() {
    return {
      loading: false,
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      formOptions: Options,
      curDate: dateFormatter(new Date().getTime(), false),
      stepTime: '00:30',
      startTime: '00:00',
      endTime: '24:00',
      tableData: [],
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        checkDate: [],
        depArea: '',
        modality: '',
        checkRoom: '',
        checkClass: [],
        week: [],
        status: '',
        beginTime: '',
        endTime: ''
      },
      rules: {
        checkDate: { type: 'array', required: true, message: '请选择记录时间', trigger: 'change' }
      },
      depAreaOptions: [],
      scheduledDepOptions: [],
      modalityOptions: [],
      checkRoomOptions: [],
      statusOptions: ['启用', '停用'],
      // 批量修改预约时段状态
      asStatusFormData: null,
      asEditDialog: false,
      asEditType: 0,
      asEidtRow: null,
      asEditAppoStatus: null,
      // 时段日志
      appoPeriodLogDlg: false,
      appoLogId: '',

      // 快速查询
      quickFilterStatus: true
    }
  },
  computed: {
    startTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        maxTime: this.formData.endTime
      }
    },
    endTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        minTime: this.formData.beginTime
      }
    }
  },
  async created() {
    await this.$getHospitalList()
    // this.search()
  },
  async mounted() {
    this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      await this.getDepAreaOptions()
      this.getScheduledDepOptions()
      this.getModalityOptions()
      this.getCheckRoomOptions()
    } catch (err) {
      console.log(err)
    }
    this.$nextTick(() => {
      this.$refs.hospAreaDepFilter && this.$refs.hospAreaDepFilter.init()
    })
  },
  methods: {
    // 时段日志
    handleLog(row) {
      this.appoLogId = row.id + ''
      this.appoPeriodLogDlg = true
    },
    // 批量修改预约时段状态
    appoAllRuleChange() {
      if (this.tableData.length === 0) {
        this.$message.warning('未查询到预约时段数据！')
        return
      }
      const _d = {
        hospitalCode: this.asStatusFormData.hospitalCode,
        dep: this.asStatusFormData.dep,
        totalCount: this.totalCount
      }
      _d.dep = _d.dep ? _d.dep : this.scheduledDepOptions.join(',')
      // console.log('dep:', _d.dep)
      if (!_d.hospitalCode) {
        this.$message.warning('请选择医院！')
        return
      } else if (!_d.dep) {
        this.$message.warning('请选择检测部门！')
        return
      }
      this.$refs.ruleTemplateDlg.init(_d)
    },
    appoRuleDlgClose() {
      this.$refs.ruleTemplateDlg.close()
    },
    // 时段条件编辑回调提交
    appoAllRuleEditSend(ruleData) {
      console.log(ruleData)
      const endTime = this.getEndTime(this.asStatusFormData.endTime)
      const params = {
        hospitalCode: this.asStatusFormData.hospitalCode,
        depArea: this.asStatusFormData.depArea,
        dep: this.asStatusFormData.dep,
        modality: this.asStatusFormData.modality,
        checkRoom: this.asStatusFormData.checkRoom,
        checkClass: this.asStatusFormData.checkClass.join(','),
        week: this.asStatusFormData.week.join(','),
        beginTime: this.asStatusFormData.beginTime ? this.asStatusFormData.beginTime + ':00' : '',
        endTime: endTime ? endTime + ':00' : '',

        'status': this.asStatusFormData.status,
        'appointmentFilters': ruleData
      }
      this.loading = true
      putAppTempDmbsetfilters(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.$message.success(res.message)
          this.$refs.ruleTemplateDlg.close()
          this.search()
        }
      })
    },
    resetParam() {
      // 重置
      this.formData = {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        depArea: '',
        modality: '',
        checkRoom: '',
        checkDate: [],
        checkClass: [],
        week: [],
        beginTime: '00:30',
        endTime: '23:30'
      }
    },
    serach1() {
      this.search()
    },
    search() {
      // 查询
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.currentPage = 1
          this.fetchData()
        }
      })
    },
    changePagenation() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.fetchData()
        }
      })
    },
    fetchData() {
      this.loading = true
      const endTime = this.getEndTime(this.formData.endTime)
      let data = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep,
        modality: this.formData.modality,
        checkRoom: this.formData.checkRoom,
        checkClass: this.formData.checkClass.join(','),
        week: this.formData.week.join(','),
        beginTime: this.formData.beginTime ? this.formData.beginTime + ':00' : '',
        endTime: endTime ? endTime + ':00' : '',
        status: this.formData.status,
        pageSize: this.pageSize, // 页面大小
        pageNumber: this.currentPage // 页码
      }
      postAppTempAdvancepages(data).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.tableData = res.content.list
          if (this.tableData) {
            this.tableData.forEach((td) => {
              let obj = this.mx_hospitalList.find((v) => {
                return td.hospitalCode === v.code
              })
              td.hospitalName = obj.name
            })
          }
          this.totalCount = res.content.totalCount
          this.asStatusFormData = JSON.parse(JSON.stringify(this.formData))
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepAreaList(params).then((res) => {
          if (res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea
      }
      return new Promise(async resolve => {
        await getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.scheduledDepOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getModalityOptions() {
      /* 检查设备列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep
      }
      return new Promise(async resolve => {
        await getModalityList(params).then((res) => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getCheckRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep,
        modality: this.formData.modality
      }
      return new Promise(async resolve => {
        await getCheckRoomList(params).then((res) => {
          if (res.code === 10000) {
            this.checkRoomOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depAreaOptions = []
          this.scheduledDepOptions = []
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.depArea = ''
          this.formData.dep = ''
          this.formData.modality = ''
          this.formData.checkRoom = ''
          this.tableData = []
          this.totalCount = 0
          this.asStatusFormData = null
          try {
            await this.getDepAreaOptions()
            this.getScheduledDepOptions()
            this.getModalityOptions()
            this.getCheckRoomOptions()
            this.search()
          } catch (err) {
            console.log(err)
          }
          this.$nextTick(() => {
            this.$refs.hospAreaDepFilter && this.$refs.hospAreaDepFilter.init()
          })
          break
        case 'depArea':
          this.scheduledDepOptions = []
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.dep = ''
          this.formData.modality = ''
          this.formData.checkRoom = ''
          try {
            await this.getScheduledDepOptions()
            this.getModalityOptions()
            this.getCheckRoomOptions()
            this.$refs.hospAreaDepFilter && this.$refs.hospAreaDepFilter.reset()
          } catch (err) {
            console.log(err)
          }
          break
        case 'dep':
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.modality = ''
          this.formData.checkRoom = ''
          try {
            await this.getModalityOptions()
            this.getCheckRoomOptions()
            this.$refs.hospAreaDepFilter && this.$refs.hospAreaDepFilter.reset()
          } catch (err) {
            console.log(err)
          }
          break
        case 'modality':
          this.checkRoomOptions = []
          this.formData.checkRoom = ''
          try {
            this.getCheckRoomOptions()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    flrDate(rowDate) {
      // console.log(dateFormatter(rowDate, false))
      // console.log(this.curDate)
      // console.log(new Date(dateFormatter(rowDate, false)).getTime() >= new Date(this.curDate).getTime())
      return new Date(dateFormatter(rowDate, false)).getTime() >= new Date(this.curDate).getTime()
    },
    dateFormatterDay(row, column, cellValue, index) {
      return cellValue ? dateFormatter(cellValue, false) : '-'
    },
    dateFormatterTime(row, column, cellValue, index) {
      return cellValue ? dateFormatter(cellValue) : '-'
    },
    statusFlr(status) {
      switch (status) {
        case '启用':
          return 'status_success'
        default:
          return 'status_danger'
      }
    },
    // 判断是否位24点，如果24点，则转为 23：59
    getEndTime(time) {
      if (!time) return ''
      const t = time.split(':')
      return t[0] * 1 === 24 ? '23:59' : time
    },

    // 快速查询返回
    treeChange(data) {
      let area = data.area
      let dep = data.dep
      let areaChange = this.formData.depArea && this.formData.depArea !== area
      this.formData.depArea = area
      this.formData.dep = dep
      if (areaChange) {
        this.getScheduledDepOptions()
      }
      this.formData.modality = ''
      this.formData.checkRoom = ''
      this.getModalityOptions()
      this.getCheckRoomOptions()
      this.search()
    }
  }
}
</script>
<style lang='scss' scoped>
.content-title{
  margin-left:4px;
  margin-bottom: 16px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  .tit{
    line-height: 34px;
  }
}
.title_btn{
  margin-left: 20px;
}
.status_edit{
  color: #FF8618;
  cursor: pointer;
  margin-left: 10px;
  &:hover{
    color: #f19238
  }
}

$appoSuccessColor: #0bd677;
$appoSuccessBgColor: rgba(11, 214, 119, 0.08);
$appoSuccessBrColor: rgba(11, 214, 112, 0.4);
$appoDefaultColor: #1890FF;
$appoDefaultBgColor: rgba(26, 144, 255, 0.08);
$appoDefaultBrColor: rgba(24, 143, 255, 0.4);
$appoDangerColor: #E37470;
$appoDangerBgColor: rgba(227, 116, 112, 0.08);
$appoDangerBrColor: rgba(235, 79, 79, 0.4);
$appoWarnColor: #FF8618;
$appoWarnBgColor: rgba(255, 136, 24, 0.08);
$appoWarnBrColor: rgba(255, 136, 24, 0.4);
$appoGreyColor: #919398;
$appoGreyBgColor: rgba(145, 147, 152, 0.08);
$appoGreyBrColor: rgba(145, 147, 152, 0.4);
.status_tag{
  display: inline-block;
  padding: 2px 6px;
  border-radius: 3px;
  border: solid 1px $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  font-size: 12px;
  color: $appoDefaultColor;
}
.status_default{
  border-color: $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  color: $appoDefaultColor;
}
.status_success{
  border-color: $appoSuccessBrColor;
  background-color: $appoSuccessBgColor;
  color: $appoSuccessColor;
}
.status_danger{
  border-color: $appoDangerBrColor;
  background-color: $appoDangerBgColor;
  color: $appoDangerColor;
}
.status_warn{
  border-color: $appoWarnBrColor;
  background-color: $appoWarnBgColor;
  color: $appoWarnColor;
}
.status_grey{
  border-color: $appoGreyBrColor;
  background-color: $appoGreyBgColor;
  color: $appoGreyColor;
}
</style>
